import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/entity/goods/detail/goods_detail_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/product_details_provider.dart';
import 'package:distribution_mall_flutter/provider/goods/product_details.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:distribution_mall_flutter/widgets/earn.dart';
import 'package:distribution_mall_flutter/widgets/input_quantity/input_quantity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:sliver_tools/sliver_tools.dart';

class ProductItems extends ConsumerWidget {
  const ProductItems({super.key});

  Widget renderItem(int index,
      {int? count,
      List<Sale> list = const [],
      bool isLogin = false,
      required BuildContext context,
      required WidgetRef ref,
      required Sale sale,
      bool? spread}) {
    double phoneWidth = MediaQuery.of(context).size.width;
    bool isSmallPhone = true; //phoneWidth <= 375;
    bool notOnSale =
        sale.onSale != true || sale.stockNum == 0 || sale.stockNum == null;
    return Container(
      key: ValueKey(sale.saleItemId),
      margin: const EdgeInsets.only(top: 24, left: 16, right: 16),
      height: isSmallPhone ? 50 : 70,
      child: Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              if (sale.imagePic != null)
                GestureDetector(
                  onTap: () {
                    appRouter.push(ReviewImageRoute(
                        images: sale.imagePic ?? '', index: index));
                  },
                  child: ImageLoader.imageNet(sale.imagePic ?? '',
                      width: isSmallPhone ? 50 : 70,
                      height: isSmallPhone ? 50 : 70,
                      fit: BoxFit.cover,
                      radius: 8),
                ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 8, top: 3, bottom: 3),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            sale.specInfos?[0].specUnit
                                    ?.split('of')
                                    .last
                                    .trim() ??
                                '',
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: isSmallPhone ? 13 : 14,
                                color: const Color(0xFF171717),
                                fontWeight: FontWeight.w600),
                          ),
                          if (isLogin) ...[
                            Container(
                              margin: const EdgeInsets.only(left: 8, right: 8),
                              height: 10,
                              width: 1,
                              color: const Color(0x29000000),
                            ),
                            Utils.currencyWidget(sale.displayUnitPrice,
                                sufText: '/${S.current.Pcs}',
                                symbolStyle: TextStyle(
                                  fontSize: isSmallPhone ? 13 : 14,
                                  color: const Color(0xFFFA2C19),
                                  fontWeight: FontWeight.w600,
                                ),
                                commonStyle: TextStyle(
                                  fontSize: isSmallPhone ? 13 : 14,
                                  color: const Color(0xFFFA2C19),
                                  fontWeight: FontWeight.w600,
                                )),
                          ]
                        ],
                      ),
                      if (isLogin)
                        Padding(
                            padding: const EdgeInsets.only(top: 2),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Utils.currencyWidget(sale.displaySalePrice,
                                    symbolStyle: const TextStyle(
                                        fontSize: 10,
                                        color: Colors.black,
                                        letterSpacing:
                                            TextConstant.letterSpacing),
                                    priceStyle: TextStyle(
                                        fontSize: isSmallPhone ? 17 : 18,
                                        color: Colors.black,
                                        letterSpacing:
                                            TextConstant.letterSpacing)),
                                // const SizedBox(
                                //   width: 7,
                                // ),
                                // EPEarn(
                                //   text: Utils.formatDouble(
                                //       sale.displayProfitPrice),
                                //   marginTop: 0,
                                // )
                              ],
                            ))
                    ],
                  ),
                ),
              ),
              // 是否在销售
              notOnSale
                  ? Container(
                      width: 68.3,
                      height: 30,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius:
                              const BorderRadius.all(Radius.circular(15)),
                          border: Border.all(
                              color: const Color.fromRGBO(220, 222, 226, 1),
                              width: 0.9)),
                      child: Text(
                        S.current.sold,
                        style: const TextStyle(
                            fontSize: 14.6,
                            color: Color.fromRGBO(134, 141, 150, 1),
                            letterSpacing: TextConstant.letterSpacing),
                      ),
                    )
                  : Visibility(
                      visible: isLogin,
                      child: SizedBox(
                        width: 98.2,
                        child: InputQty.int(
                          minVal: 0,
                          maxVal: sale.stockNum ?? 1,
                          steps: sale.stepQuantity ?? 1,
                          initVal: 0,
                          isIntrinsicWidth: false,
                          qtyFormProps: const QtyFormProps(
                            cursorHeight: 15,
                            style: TextStyle(height: 0.9),
                            keyboardType: TextInputType.number,
                          ),
                          decoration: const QtyDecorationProps(
                            constraints:
                                BoxConstraints(maxHeight: 31, minHeight: 31),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                  Radius.circular(RadiusConstant.edge20)),
                              borderSide: BorderSide(
                                color: Color.fromRGBO(220, 222, 226, 1),
                                width: 0.9,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Color.fromRGBO(220, 222, 226, 1),
                                  width: 0.9,
                                ),
                                borderRadius: BorderRadius.all(
                                    Radius.circular(RadiusConstant.edge20))),
                            iconWidth: 30.9,
                            iconHeight: 30.9,
                            btnColor: Colors.black,
                            width: 1,
                            borderShape: BorderShapeBtn.circle,
                            border: OutlineInputBorder(
                                borderSide: BorderSide(
                                    color: Colors.transparent, width: 0.9)),
                            contentPadding: EdgeInsets.symmetric(
                                horizontal: EdgeConstant.edge5),
                          ),
                          onQtyChanged: (val) {
                            ref
                                .read(pDetailProvider.notifier)
                                .setSkuItems(sale.saleItemId, val as int);
                            ref
                                .read(productDetailsShowGuideProvider.notifier)
                                .showGuide();
                          },
                        ),
                      ))
            ],
          ),
          Visibility(
              visible: notOnSale,
              child: Positioned(
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
                child: Container(
                  color: const Color.fromRGBO(255, 255, 255, 0.5),
                ),
              )),
        ],
      ),
    );
  }

  Widget renderExpand(WidgetRef? ref, bool? spread) {
    return Container(
      alignment: Alignment.bottomCenter,
      padding: const EdgeInsets.only(bottom: 12.7),
      decoration: const BoxDecoration(
        border: Border(
            bottom: BorderSide(width: 0.9, color: ColorConstant.grey233_4)),
        gradient: LinearGradient(colors: [
          Color(0x00ffffff),
          Color(0xffffffff),
        ], stops: [
          0.0,
          0.77
        ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
      ),
      child: GestureDetector(
        onTap: () {
          ref?.read(pDetailProvider.notifier).triggerSpread();
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              spread == true ? S.current.pack : S.current.More,
              style: const TextStyle(
                  color: Color.fromRGBO(134, 141, 150, 1),
                  letterSpacing: TextConstant.letterSpacing,
                  fontSize: 18),
            ),
            Icon(
              spread == false
                  ? Icons.keyboard_arrow_down_outlined
                  : Icons.keyboard_arrow_up_outlined,
              color: const Color.fromRGBO(134, 141, 150, 0.5),
              size: 12,
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final modal = ref.watch(pDetailProvider);
    final modalNotifier = ref.watch(pDetailProvider.notifier);
    bool isLogin = ref.watch(loginStateProvider);

    return MultiSliver(
      // pushPinnedChildren: true,
      children: [
        SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
            return renderItem(index,
                isLogin: isLogin,
                sale: modal.saleInfos[index],
                count: modal.saleInfos.length,
                ref: ref,
                spread: modal.spread,
                context: context);
          }, childCount: modal.saleInfos.length),
        ),
        // SliverVisibility(
        //     visible: modal.saleInfos.length > 3,
        //     sliver: SliverAnimatedPaintExtent(
        //         duration: const Duration(milliseconds: 800),
        //         // curve: Curves.bounceOut,
        //         curve: Curves.elasticOut,
        //         // curve: Curves.easeOutBack,
        //         child: SliverList(
        //             delegate: SliverChildBuilderDelegate(((context, index) {
        //           return renderItem(index + 3,
        //               isLogin: isLogin,
        //               sale: modal.saleInfos[index + 3],
        //               count: modal.saleInfos.length,
        //               ref: ref,
        //               spread: modal.spread, context: context);
        //         }),
        //                 childCount:
        //                     modal.spread ? modal.saleInfos.length - 3 : 0)))),
        SliverVisibility(
            visible: modal.spread == true,
            sliver: SliverToBoxAdapter(
                child: GestureDetector(
              onTap: () {
                ref.read(pDetailProvider.notifier).triggerSpread();
              },
              child: renderExpand(ref, modal.spread),
            )))
      ],
    );
  }
}
